import os
import re

from app.logic.utils.filepath import SRC_DIR, PREPROCESS_DIR

"""
预处理、去除注释
"""


class GeneratePreprocessing:
    """
    预处理
    work_dir: 工作目录
    project_path: 项目路径
    """

    def __init__(self, work_path_dir, project_path_dir):
        self.workspace = os.path.join(work_path_dir, str(project_path_dir))
        self.src_dir = os.path.join(work_path_dir, str(project_path_dir), SRC_DIR)
        self.pre_dir = os.path.join(work_path_dir, str(project_path_dir), PREPROCESS_DIR)

        # 确保 preprocess 存储目录存在
        os.makedirs(self.pre_dir, exist_ok=True)

    def remove_comments(self, java_code):
        """
        去除 Java 文件中的注释
        :param java_code: Java 源代码字符串
        :return: 去除注释后的代码
        """
        # 去除多行注释
        java_code = re.sub(r'/\\*.*?\\*/', '', java_code, flags=re.DOTALL)
        # 去除单行注释
        java_code = re.sub(r'//.*', '', java_code)
        return java_code

    def process_files(self):
        """
        处理源代码文件，去除注释并将结果存储到预处理目录
        """
        for root, _, files in os.walk(self.src_dir):
            for file in files:
                if file.endswith('.java'):
                    src_file_path = os.path.join(root, file)
                    with open(src_file_path, 'r', encoding='utf-8') as f:
                        java_code = f.read()

                    # 去除注释
                    processed_code = self.remove_comments(java_code)
                    file_name = os.path.basename(src_file_path)  # 获取文件名
                    preprocessed_file_path = os.path.join(self.pre_dir, file_name)

                    # 确保目标目录存在
                    os.makedirs(os.path.dirname(preprocessed_file_path), exist_ok=True)

                    # 写入预处理后的代码
                    with open(preprocessed_file_path, 'w', encoding='utf-8') as f:
                        f.write(processed_code)

                    print(f"Preprocessed {src_file_path} and saved to {preprocessed_file_path}")

    def run(self):
        """
        执行预处理
        """
        self.process_files()


def gen_preprocessor(work_dir, project_path):
    preprocessor = GeneratePreprocessing(work_dir, project_path)
    preprocessor.run()


# 使用方法示例
if __name__ == "__main__":
    work_dir = '../../../data'  # 请修改为实际路径
    project_path = '29'  # 请修改为实际项目路径

    preprocessor = GeneratePreprocessing(work_dir, project_path)
    preprocessor.run()
